<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    //注册
    public function signup()
    {
        return view('signup');
    }
    //登录
    public function login()
    {
        return view('login');
    }
    //修改
    public function update(Request $request)
    {
        $res = DB::table('user')->where('id',session('uid'))->first();
        return view('update',['data'=>$res]);
    }
    //退出
    public function loginout(){
        session()->forget('uid');
        return redirect()->route('ucenter');
    }
    //个人中心
    public function ucenter(){
        //判断是否登录
        if (session()->has('uid')){
            $res = DB::table('user')->where('id',session('uid'))->first();
            $list = DB::table('user')
                ->join('love_list',function ($join){
                    $join->on('user.id','=','love_list.uid')
                        ->where('user.id',session('uid'));
                })
                ->get();
            return view('ucenter',['data'=>$res,'list'=>$list]);
        }else{
            return view('ucenter');
        }
    }
    //删除一个发布的内容
    public function del(Request $request)
    {
        $id = $request->id;
        $res = DB::table('love_list')->where('id',$id)->delete();
        echo $res;
    }
    //验证登录
    public function checkLogin(Request $request)
    {
        $data = $request->all();
        $res = DB::table('user')->where(['qq'=>$data['qq']])->first();

        if ($res){
            if (Hash::check($data['password'],$res->password)){
                session(['uid'=>$res->id]);
                echo 'true';
            }
        }
    }
    //注册用户
    public function signupuser(Request $request)
    {
        $data = $request->all();

        $check = DB::table('user')->where('qq', $data['qq'])->first();

        if (!$check) {
            $data['password'] = Hash::make($data['password']);
            $res = DB::table('user')->insertGetId($data);
            if ($res) {
                session(['uid' => $res]);
                echo 'true';
            }
        }
    }
    //修改用户信息
    public function updateuser(Request $request)
    {
        $data = $request->all();
        $user = DB::table('user')->where('id',session('uid'))->first();

        if (Hash::check($data['oldpwd'],$user->password)){
            $arr = array(
                'username'=>$data['username'],
                'password'=>Hash::make($data['password'])
            );
            $res = DB::table('user')->where('id',session('uid'))->update($arr);
            echo $res;
        }else{
            echo 'false';
        }
    }
}
